package com.op.studyingliteapp.activity.homeactivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bluemor.reddotface.util.Util;
import com.bluemor.reddotface.view.DragLayout;
import com.bluemor.reddotface.view.DragLayout.DragListener;
import com.nineoldandroids.view.ViewHelper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.op.studyingliteapp.R;
import com.op.studyingliteapp.activity.CourseActivity;
import com.op.studyingliteapp.activity.PictureActivity;
import com.op.studyingliteapp.activity.UserInformationActivity;
import com.op.studyingliteapp.bean.CourseBean;
import com.op.studyingliteapp.bean.UserBean;
import com.op.studyingliteapp.common.Common;
import com.op.studyingliteapp.common.CourseUrl;
import com.op.studyingliteapp.database.dao.CourseDao;
import com.op.studyingliteapp.database.dao.UserDao;
import com.op.studyingliteapp.widget.RoundImageView;
import com.op.util.SharedPreferenceUtil;
import com.op.util.StringUtils;
import com.op.util.asynctask.HttpPostTask;
import com.op.util.asynctask.OnTaskProcessListener;
import com.op.util.network.NetworkUtils;

/**
 * @author Michael
 * @date Jul 11, 2015
 */
public class HomeActivity extends Activity {
	private String getCourseUserId;
	public static ContentResolver contentResolver;
	private DragLayout sidebar;
	// private GridView courseGridView;
	private ListView lv;
	private RoundImageView iv_icon; // 头像

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 修改控件布局背景
		Resources resources = HomeActivity.this.getResources();
		// 判断是否是第一次进入HomeActivity
		SharedPreferences preferences = getSharedPreferences("StudyingLite", Context.MODE_PRIVATE);
		Boolean needUpdataData = preferences.getBoolean("needUpdataData", true);

		// 前一个参数是去userId的key，我之前设置的是userId本身，所以这样取,第二个参数为缺省值，如果preference中不存在该key，将返回缺省值
		getCourseUserId = preferences.getString(Common.Prefs.USER_ID, "");
		// 判断Wifi和GSM网络状况，被邱老师改过
		if (NetworkUtils.isNetworkAvailable(this)) {
			getCoursePost();
			if (needUpdataData) {
				// 如果是第一次进入HomeActivity，从网络 获取课程列表
				getCoursePost();
			}
		} else {
			// 如果没有Wifi无连接 则从数据库中取课程列表
			CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
			List<CourseBean> courses = courseDao.getCoursesByUserId(getCourseUserId);

			String str = courses.size() + "\\";
			for (int i = 0; i < courses.size(); i++) {
				str += courses.get(i).getName() + "\\";
			}
		}
		setContentView(R.layout.activity_home);
		setGridView();
		Util.initImageLoader(this);// 有用的
		initDragLayout();
		initView();

	}

	// ******************************************************************侧边栏

	private void initDragLayout() {
		sidebar = (DragLayout) findViewById(R.id.dl);
		sidebar.setDragListener(new DragListener() {
			@Override
			public void onOpen() {
				lv.smoothScrollToPosition(new Random().nextInt(30));

			}

			@Override
			public void onClose() {

			}

			@Override
			public void onDrag(float percent) {
				ViewHelper.setAlpha(iv_icon, 1 - percent);
			}
		});

		ImageView use_image = (ImageView) findViewById(R.id.use_image);
		use_image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(HomeActivity.this, UserInformationActivity.class);
				startActivity(intent);
			}
		});

	}

	private void initView() {
		//侧边栏的的listview
		 ArrayList<SidebarData> Sidebarlsitview = new ArrayList<SidebarData>();

		 Sidebarlsitview.add(new SidebarData("投影",R.drawable.projection));
		 Sidebarlsitview.add(new SidebarData("截图",R.drawable.screenshot));
		 Sidebarlsitview.add(new SidebarData("设置",R.drawable.setting));
		SidebarAdapter  sidebarAdapter =new SidebarAdapter(HomeActivity.this, Sidebarlsitview);
		lv = (ListView) findViewById(R.id.lv);
		lv.setAdapter(sidebarAdapter);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				
			}
		});

		
		SharedPreferences getUser = SharedPreferenceUtil.getInstance(HomeActivity.this);
		UserDao userDao = new UserDao(HomeActivity.this);
		UserBean userBean = userDao.getUserByUserId(getUser.getString("userId", "未知"));
		
		/*顶部导航栏
		 * 点击头像进入侧边栏
		 */
		iv_icon = (RoundImageView) findViewById(R.id.iv_icon);
		ImageLoader.getInstance().displayImage(userBean.getImageUrl(), iv_icon);
		iv_icon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				sidebar.open();
			}
		});
		/**
		 * 侧边栏的头像
		 */
		RoundImageView use_image = (RoundImageView) findViewById(R.id.use_image);
		ImageLoader.getInstance().displayImage(userBean.getImageUrl(), use_image);
		use_image.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(HomeActivity.this, UserInformationActivity.class);
				startActivity(intent);
			}
		});
		
		TextView use_name = (TextView) findViewById(R.id.use_name);
		use_name.setText(userBean.getName());
	}

	// **************************************************************************************

	/**
	 * 设置主页的GridView
	 */
	public void setGridView() {
		GridView courseGridView = (GridView) findViewById(R.id.course_gridview);
		final HomeCoursesAdapter mAdapter = new HomeCoursesAdapter(getApplication());
		courseGridView.setAdapter(mAdapter);
		courseGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 将点击的课程的Id添加到SharedPreferences
				Map<String, Object> prefsMap = new HashMap<String, Object>();
				prefsMap.put(Common.Prefs.COURSE_ID, mAdapter.getCourseId(position));
				SharedPreferenceUtil.saveData(HomeActivity.this, prefsMap);
				Intent intent = new Intent(HomeActivity.this, CourseActivity.class);
				intent.putExtra("CourseName",mAdapter.getItem(position).getName());
				startActivity(intent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_home, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

//	 private void setView() {
//	  Button pdfBtn = (Button) this.findViewById(R.id.pdf);
//	  pdfBtn.setOnClickListener(new PdfBtnListener());
//	  Button pictureBtn = (Button) this.findViewById(R.id.picture);
//	  pictureBtn.setOnClickListener(new PictureBtnListener());
//	  Button photoBtn = (Button) this.findViewById(R.id.photo);
//	  photoBtn.setOnClickListener(new PhotoBtnListener());
//	 }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Uri uri = data.getData();
			Log.i("uri", uri.toString());
			contentResolver = this.getContentResolver();
			try {
				Intent intent = new Intent(this, PictureActivity.class);
				Bundle bundle = new Bundle();
				bundle.putParcelable("uri", uri);
				intent.putExtras(bundle);

				startActivity(intent);
			} catch (Exception e) {
				Log.e("Exception", e.getMessage(), e);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void getCoursePost() {
		// 做异步请求
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Common.Prefs.USER_ID, getCourseUserId));
		HttpPostTask task = new HttpPostTask(HomeActivity.this, CourseUrl.GET_COURSE_BY_USER_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
				// 清空所有课程
				CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
				courseDao.empty();
			}

			@Override
			public void completed(String result) {

				// 存储数据
				try {
					if (!StringUtils.isEmptyOrStringNull(result)) {
						JSONObject jsonObject = new JSONObject(result);
						Log.i("------------------------------", "dsa______________________________________________:" + result);

						JSONArray jsonArray = jsonObject.getJSONObject("resultMap").getJSONArray("courseList");

						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject courseObject = jsonArray.getJSONObject(i);
							CourseBean courseBean = new CourseBean();
							courseBean.fillAttributeByJson(courseObject);
							CourseDao courseDao = new CourseDao(HomeActivity.this, getCourseUserId);
							courseDao.insert(courseBean);
							initView();
							setGridView();
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

		});
		task.execute();
		// 将判断是否第一次登陆的数据放入SharedPreference
		HashMap<String, Object> needUpdataData = new HashMap<String, Object>();
		needUpdataData.put("needUpdataData", false);
		SharedPreferenceUtil.saveData(HomeActivity.this, needUpdataData);
	}
}
